import { onMounted, onUnmounted, ref } from 'vue'

/**
 * @description 获取鼠标移动位置
 * @function useMouse()
 * @return object = { x, y }
 * @example
   <script setup lang="ts">
     const { x, y } = useMouse()
   </script>

   <template>
     <div>pos: {{x}}, {{y}}</div>
   </template>
 */
export const useMouse = () => {
  const x = ref(0)
  const y = ref(0)

  function getMouse(e: MouseEvent) {
    const { x: ex, pageX, clientX, screenX, y: ey, pageY, clientY, screenY } = e
    x.value = ex || pageX || clientX || screenX
    y.value = ey || pageY || clientY || screenY
  }

  onMounted(() => {
    window.addEventListener('mousemove', getMouse)
  })
  onUnmounted(() => {
    window.removeEventListener('mousemove', getMouse)
  })

  return {
    x,
    y
  }
}
